package com.wang.mvchain.outer.service.implay;

import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeMap;

import javax.xml.bind.DatatypeConverter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.common.util.EncryptUtil;
import com.wang.mvchain.common.util.HTTPUtil;
import com.wang.mvchain.outer.service.ITradeService;

/**
 * 比特币中国的API工具
 * 
 * @author wangsh
 *
 */
public class BtcChinaTradeServiceImplay extends BaseTradeService implements ITradeService {
	// 登陆验证的信息,可从网站模板中查找
	private JSONObject authJSON;
	private static long generatedId = 1;

	@Override
	public int findWebsiteId() {
		return 9;
	}

	/**
	 * 获取请求时间
	 * 获取nonce的值
	 * @return
	 */
	public String findReqtime() 
	{
		long lastNonce = 0l;
		try
		{
			Thread.sleep(10);
		} catch (InterruptedException e1)
		{
		}
		
	    long newNonce = System.currentTimeMillis() * 1000;

	    while (newNonce == lastNonce) {
	      newNonce++;
	    }

	    lastNonce = newNonce;

	    return newNonce+"";
	  }

	public static long getGeneratedId() {

		return generatedId++;
	}

	/**
	 * 获取签名方式
	 * 
	 * @return
	 */
	private String authSign(Map<String, String> condMap) {
		StringBuffer sb = new StringBuffer();
		for (Iterator iterator = condMap.entrySet().iterator(); iterator.hasNext();) {
			Entry me = (Entry) iterator.next();
			String key = me.getKey() + "";
			String value = me.getValue() + "";
			if ("requestURL".equalsIgnoreCase(key)) {
				continue;
			}
			sb.append(key + "=" + value + "&");
		}
		if (sb.toString().lastIndexOf("&") != -1) {
			sb.delete(sb.lastIndexOf("&"), sb.length());
		}
		// ConstatFinalUtil.OUTER_LOG.info(sb);
		return EncryptUtil.hmacSHA512(sb.toString(), authJSON.get("Secret") + "");
	}

	/**
	 * 获取用户基本信息
	 * {"method":"getAccountInfo","params":[],"id":1}
	   {"result":{"profile":{"username":"121951255@qq.com","trade_password_enabled":true,"otp_enabled":true,"trade_fee":0,"trade_fee_cnyltc":0,"trade_fee_btcltc":0,"daily_btc_limit":10,"daily_ltc_limit":400,"btc_deposit_address":"1JbhM51CfQFXvRkDXoJcxrMPd7hg8tcMBE","btc_withdrawal_address":"","ltc_deposit_address":"LaAdgkR6nc2RcyStdSftEz2VMhzNz3zQWS","ltc_withdrawal_address":"","api_key_permission":7,"id_verify":0},"balance":{"btc":{"currency":"BTC","symbol":"\u0e3f","amount":"0.00000000","amount_integer":"0","amount_decimal":8},"ltc":{"currency":"LTC","symbol":"\u0141","amount":"0.00000000","amount_integer":"0","amount_decimal":8},"cny":{"currency":"CNY","symbol":"\u00a5","amount":"0.00000","amount_integer":"0","amount_decimal":5}},"frozen":{"btc":{"currency":"BTC","symbol":"\u0e3f","amount":"0.00000000","amount_integer":"0","amount_decimal":8},"ltc":{"currency":"LTC","symbol":"\u0141","amount":"0.00000000","amount_integer":"0","amount_decimal":8},"cny":{"currency":"CNY","symbol":"\u00a5","amount":"0.00000","amount_integer":"0","amount_decimal":5}},"loan":{"btc":{"currency":"BTC","symbol":"\u0e3f","amount":"0.00000000","amount_integer":"0","amount_decimal":8},"cny":{"currency":"CNY","symbol":"\u00a5","amount":"0.00000","amount_integer":"0","amount_decimal":5}}},"id":"1"}	
	 * @return
	 */
	public JSONObject getUserInfo(Map<String, String> paramsMap) {
		long st = System.currentTimeMillis();
		// 拼装目标数据
		JSONObject resultJSON = new JSONObject();

		Map<String, String> requestMap = new HashMap<String, String>();
		HTTPUtil httpUtil = new HTTPUtil();
		
		String nonce = this.findReqtime();
		long id = this.getGeneratedId();
		String params = String.format("tonce=%s&accesskey=%s&requestmethod=%s&id=%d&method=%s&params=%s", nonce, authJSON.getString("Key"), "post", id, "getAccountInfo", "");
	    //ConstatFinalUtil.SYS_LOG.error("signature message: "+params );
	    String hash=EncryptUtil.BtcChinaHmacSHA1(params,authJSON.getString("Secret"));
	    //System.out.println(hash);
	    String userpass = authJSON.getString("Key")+ ":" + hash;
	    String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
	    //System.out.println(basicAuth);
	    
	    String postStr = String.format("{\"method\": \"%s\", \"params\": %s, \"id\": %s}", "getAccountInfo", "[]", id);
	    
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Json-Rpc-Tonce", nonce);
		headerMap.put("Authorization", basicAuth);
		headerMap.put("requestURL", "https://api.btcchina.com/api_trade_v1.php");
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, postStr);
			//ConstatFinalUtil.SYS_LOG.error(res);
			responseJSON = (JSONObject) JSON.parse(result);
			if (responseJSON != null && responseJSON.get("result")!=null ) {
				JSONObject dataJSON = new JSONObject();
				JSONObject balanceJSON = new JSONObject();
				JSONObject frozenJSON = new JSONObject();
				try {
					JSONObject resJSON = (JSONObject) responseJSON.get("result");
					if(resJSON.size()>0 && resJSON.getJSONObject("balance")!=null){
						JSONObject balance = resJSON.getJSONObject("balance");
						if(balance!=null && balance.getJSONObject("btc")!=null){
							JSONObject btc = balance.getJSONObject("btc");
							balanceJSON.put("btc", btc.getString("amount"));
						}
						if(balance!=null && balance.getJSONObject("ltc")!=null){
							JSONObject ltc = balance.getJSONObject("ltc");
							balanceJSON.put("ltc", ltc.getString("amount"));
						}
						if(balance!=null && balance.getJSONObject("cny")!=null){
							JSONObject cny = balance.getJSONObject("cny");
							balanceJSON.put("cny", cny.getString("amount"));
						}
						dataJSON.put("balance", balanceJSON);
					}
					if(!balanceJSON.containsKey("btc")){
						balanceJSON.put("btc", "0");
					}
					if(!balanceJSON.containsKey("ltc")){
						balanceJSON.put("ltc", "0");
					}
					if(!balanceJSON.containsKey("cny")){
						balanceJSON.put("cny", "0");
					}
					if(resJSON.size()>0 && resJSON.getJSONObject("frozen")!=null){
						JSONObject frozen = resJSON.getJSONObject("frozen");
						if(frozen!=null && frozen.getJSONObject("btc")!=null){
							JSONObject btc = frozen.getJSONObject("btc");
							frozenJSON.put("btc", btc.getString("amount"));
						}
						if(frozen!=null && frozen.getJSONObject("ltc")!=null){
							JSONObject ltc = frozen.getJSONObject("ltc");
							frozenJSON.put("ltc", ltc.getString("amount"));
						}
						if(frozen!=null && frozen.getJSONObject("cny")!=null){
							JSONObject cny = frozen.getJSONObject("cny");
							frozenJSON.put("cny", cny.getString("amount"));
						}
						dataJSON.put("fund", frozenJSON);
					}
					if(!frozenJSON.containsKey("btc")){
						frozenJSON.put("btc", "0");
					}
					if(!frozenJSON.containsKey("ltc")){
						frozenJSON.put("ltc", "0");
					}
					if(!frozenJSON.containsKey("cny")){
						frozenJSON.put("cny", "0");
					}
				} catch (ClassCastException ce) {
					balanceJSON.put("btc", "0");
					balanceJSON.put("ltc", "0");
					balanceJSON.put("cny", "0");
					balanceJSON.put("usd", "0");
					dataJSON.put("balance", balanceJSON);
					frozenJSON.put("btc", "0");
					frozenJSON.put("ltc", "0");
					frozenJSON.put("cny", "0");
					frozenJSON.put("usd", "0");
					dataJSON.put("balance", frozenJSON);
				}

				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			} else {
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:"
						+ responseJSON.get("error"));
			}
			// ConstatFinalUtil.OUTER_LOG.info(this.findid() + "--获取用户信息返回.--" +
			// responseJSON);
		} catch (Exception e) {
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户信息失败." + requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis();
		resultJSON.put("consume", (ed - st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 下单交易
	 * {"method":"buyOrder2","params":[500,1],"id":1}
	   {"result":12345,"id":"1"}
	   {"method":"sellOrder2","params":[500,1],"id":1}
 	   {"result":12345,"id":"1"}
 	   {"error":{"code":-32004,"message":"Insufficient balance","data":{}},"id":"1"}	
	 * @return
	 */
	public JSONObject trade(Map<String, String> paramsMap) {
		long st = System.currentTimeMillis();
		// 拼装目标数据
		JSONObject resultJSON = new JSONObject();
		// 开发版本
		if ("1".equalsIgnoreCase(ConstatFinalUtil.SYS_BUNDLE.getString("dev.version"))) {
			// 模拟假数据
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("order_id", new Random().nextInt(10000));

			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "---模拟下单---" + paramsMap);
			return resultJSON;
		}

		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> requestMap = new HashMap<String, String>();
		String market = this.convertMoneyType(paramsMap.get("moneytype"));
		// 买还是卖.0:买,1:卖
		String method="";
		if ("0".equalsIgnoreCase(paramsMap.get("type"))) {
			method="buyOrder2";
		} else if ("1".equalsIgnoreCase(paramsMap.get("type"))) {
			method="sellOrder2";
		}
		
		String paramsStr="[\""+paramsMap.get("price")+"\",\""+paramsMap.get("amount") +"\",\""+market+"\"]";
		String nonce = this.findReqtime();
		long id = this.getGeneratedId();
		String params = String.format("tonce=%s&accesskey=%s&requestmethod=%s&id=%d&method=%s&params=%s", nonce, authJSON.getString("Key"), "post", id, method, paramsMap.get("price")+","+paramsMap.get("amount")+","+market);
	    //ConstatFinalUtil.SYS_LOG.error("signature message: "+params );
	    String hash=EncryptUtil.BtcChinaHmacSHA1(params,authJSON.getString("Secret"));
	    //System.out.println(hash);
	    String userpass = authJSON.getString("Key")+ ":" + hash;
	    String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
	    //System.out.println(basicAuth);
	    
	    String postStr = String.format("{\"method\": \"%s\", \"params\": %s, \"id\": %s}", 
	    		method, paramsStr, id);
	    
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Json-Rpc-Tonce", nonce);
		headerMap.put("Authorization", basicAuth);
		headerMap.put("requestURL", "https://api.btcchina.com/api_trade_v1.php");
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, postStr);
			//ConstatFinalUtil.SYS_LOG.error(res);
			responseJSON = (JSONObject) JSON.parse(result);

			if (responseJSON != null && responseJSON.containsKey("result")) {
				JSONObject dataJSON = new JSONObject();
				dataJSON.put("order_id", responseJSON.get("result"));
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			} else {
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:"
						+ responseJSON.get("error"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--下单交易返回--原始信息:" + result
					+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e) {
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "下单交易失败." + requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis();
		resultJSON.put("consume", (ed - st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 撤销订单
	 * {"result":true,"id":"1"}
	 * {"error":{"code":-32005,"data":{},"message":"Invalid order_id"},"id":"1"}
	 * @return
	 */
	public JSONObject cancelOrder(Map<String, String> paramsMap) {
		long st = System.currentTimeMillis();
		// 拼装目标数据
		JSONObject resultJSON = new JSONObject();

		// 开发版本
		if ("1".equalsIgnoreCase(ConstatFinalUtil.SYS_BUNDLE.getString("dev.version"))) {
			// 模拟假数据
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("order_id", paramsMap.get("order_id"));

			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "---模拟下单---" + paramsMap);
			return resultJSON;
		}

		Map<String, String> requestMap = new HashMap<String, String>();
		String market = this.convertMoneyType(paramsMap.get("moneytype"));
		HTTPUtil httpUtil = new HTTPUtil();
		String paramsStr="["+paramsMap.get("order_id")+",\""+market+"\"]";
		String nonce = this.findReqtime();
		long id = this.getGeneratedId();
		String params = String.format("tonce=%s&accesskey=%s&requestmethod=%s&id=%d&method=%s&params=%s", nonce, authJSON.getString("Key"), "post", id, "cancelOrder", paramsMap.get("order_id")+","+market);
	    //ConstatFinalUtil.SYS_LOG.error("signature message: "+params );
	    String hash=EncryptUtil.BtcChinaHmacSHA1(params,authJSON.getString("Secret"));
	    //System.out.println(hash);
	    String userpass = authJSON.getString("Key")+ ":" + hash;
	    String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
	    //System.out.println(basicAuth);
	    
	    String postStr = String.format("{\"method\": \"%s\", \"params\": %s, \"id\": %s}", 
	    		"cancelOrder", paramsStr, id);
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Json-Rpc-Tonce", nonce);
		headerMap.put("Authorization", basicAuth);
		headerMap.put("requestURL", "https://api.btcchina.com/api_trade_v1.php");
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, postStr);
			responseJSON = (JSONObject) JSON.parse(result);
			// ConstatFinalUtil.SYS_LOG.info("=--==>" + response);
			if (responseJSON != null && responseJSON.containsKey("result")) {
				if (responseJSON.getString("result").equalsIgnoreCase("true")) {
					JSONObject dataJSON = new JSONObject();
					dataJSON.put("order_id", paramsMap.get("order_id"));
					resultJSON.put("data", dataJSON);
				} else {
					resultJSON.put("data", new JSONObject());
				}

				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			} else {
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:"
						+ responseJSON.get("error"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--撤销订单返回.--原始信息:" + result
					+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e) {
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "撤销订单失败." + requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis();
		resultJSON.put("consume", (ed - st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 获取用户挂单
	 * 
	 * {"result":{"order_btccny":[{"id":13942927,"type":"bid","price":"2000.00","currency":"CNY","amount":"0.00100000","amount_original":"0.00100000","date":1396255376,"status":"open"},{"id":13942807,"type":"bid","price":"2000.00","currency":"CNY","amount":"0.00100000","amount_original":"0.00100000","date":1396255245,"status":"open"}],"order_ltccny":[],"order_ltcbtc":[]},"id":"1"}
	 * {"id":"1","result":{"date":1419300134,"order_btccny":[],"order_ltcbtc":[],"order_ltccny":[]}}
	 * @param args
	 */
	public JSONObject getOrders(Map<String, String> paramsMap) {
		long st = System.currentTimeMillis();
		// 拼装目标数据
		JSONObject resultJSON = new JSONObject();

		// 开发版本
		if ("1".equalsIgnoreCase(ConstatFinalUtil.SYS_BUNDLE.getString("dev.version"))) {
			// 模拟假数据
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("ordersList", new JSONArray());

			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "---模拟下单---" + paramsMap);
			return resultJSON;
		}
		
		HTTPUtil httpUtil = new HTTPUtil();
		String market = this.convertMoneyType(paramsMap.get("moneytype"));
		String paramsStr="[true,\""+market+"\"]";
		String nonce = this.findReqtime();
		long id = this.getGeneratedId();
		String params = String.format("tonce=%s&accesskey=%s&requestmethod=%s&id=%d&method=%s&params=%s", nonce, authJSON.getString("Key"), "post", id, "getOrders", "true,"+market+"");
	    //ConstatFinalUtil.SYS_LOG.error("signature message: "+params );
	    String hash=EncryptUtil.BtcChinaHmacSHA1(params,authJSON.getString("Secret"));
	    //System.out.println(hash);
	    String userpass = authJSON.getString("Key")+ ":" + hash;
	    String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
	    //System.out.println(basicAuth);
	    
	    String postStr = String.format("{\"method\": \"%s\", \"params\": %s, \"id\": %s}", 
	    		"getOrders", paramsStr, id);
	    
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Json-Rpc-Tonce", nonce);
		headerMap.put("Authorization", basicAuth);
		headerMap.put("requestURL", "https://api.btcchina.com/api_trade_v1.php");
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, postStr);
			//ConstatFinalUtil.SYS_LOG.info(res);
			responseJSON = (JSONObject) JSON.parse(result);
			if (responseJSON != null && responseJSON.get("result")!=null) {
				JSONObject dataJSON = new JSONObject();
				JSONObject resultResJSON = (JSONObject) responseJSON.get("result");
				JSONArray ordersResArr = new JSONArray();
				if(market.equals("ALL")){
					JSONArray returnJSON = (JSONArray) resultResJSON.get("order_btccny");
					if (returnJSON != null && returnJSON.size() > 0) {
						for (Object item : returnJSON) {
							JSONObject valJSON = (JSONObject) item;

							JSONObject ordersResJSON = new JSONObject();
							ordersResJSON.put("order_id", valJSON.getString("id"));
							ordersResJSON.put("price", valJSON.get("price") + "");
							ordersResJSON.put("amount", valJSON.get("amount_original") + "");
							
							//处理下单时间
							Date createDate = new Date(Long.valueOf(valJSON.get("date") + "") * 1000);
							ordersResJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
							String type = valJSON.getString("type");
							ordersResJSON.put("deal_amount", Double.valueOf(valJSON.get("amount_original") + "") - Double.valueOf(valJSON.getString("amount") + ""));

							ordersResJSON.put("symbol", "btc_cny");

							if ("bid".equalsIgnoreCase(type)) {
								type = "0";
							} else if ("ask".equalsIgnoreCase(type)) {
								type = "1";
							}
							ordersResJSON.put("type", type + "");
							ordersResJSON.put("status", valJSON.get("status") + "");

							ordersResArr.add(ordersResJSON);
						}
					}
					returnJSON = (JSONArray) resultResJSON.get("order_ltccny");
					if (returnJSON != null && returnJSON.size() > 0) {
						for (Object item : returnJSON) {
							JSONObject valJSON = (JSONObject) item;

							JSONObject ordersResJSON = new JSONObject();
							ordersResJSON.put("order_id", valJSON.getString("id"));
							ordersResJSON.put("price", valJSON.get("price") + "");
							ordersResJSON.put("amount", valJSON.get("amount_original") + "");
							//处理下单时间
							Date createDate = new Date(Long.valueOf(valJSON.get("date") + "") * 1000);
							ordersResJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
							String type = valJSON.getString("type");
							ordersResJSON.put("deal_amount", Double.valueOf(valJSON.get("amount_original") + "") - Double.valueOf(valJSON.getString("amount") + ""));

							ordersResJSON.put("symbol", "ltc_cny");

							if ("bid".equalsIgnoreCase(type)) {
								type = "0";
							} else if ("ask".equalsIgnoreCase(type)) {
								type = "1";
							}
							ordersResJSON.put("type", type + "");
							ordersResJSON.put("status", valJSON.get("status") + "");

							ordersResArr.add(ordersResJSON);
						}
					}
					returnJSON = (JSONArray) resultResJSON.get("order_ltcbtc");
					if (returnJSON != null && returnJSON.size() > 0) {
						for (Object item : returnJSON) {
							JSONObject valJSON = (JSONObject) item;

							JSONObject ordersResJSON = new JSONObject();
							ordersResJSON.put("order_id", valJSON.getString("id"));
							ordersResJSON.put("price", valJSON.get("price") + "");
							ordersResJSON.put("amount", valJSON.get("amount_original") + "");
							String type = valJSON.getString("type");
							//处理下单时间
							Date createDate = new Date(Long.valueOf(valJSON.get("date") + "") * 1000);
							ordersResJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
							ordersResJSON.put("deal_amount", Double.valueOf(valJSON.get("amount_original") + "") - Double.valueOf(valJSON.getString("amount") + ""));

							ordersResJSON.put("symbol", "ltc_btc");

							if ("bid".equalsIgnoreCase(type)) {
								type = "0";
							} else if ("ask".equalsIgnoreCase(type)) {
								type = "1";
							}
							ordersResJSON.put("type", type + "");
							ordersResJSON.put("status", valJSON.get("status") + "");

							ordersResArr.add(ordersResJSON);
						}
					}
				}else if(market.equals("BTCCNY")){
					JSONArray returnJSON = (JSONArray) resultResJSON.get("order");
					if (returnJSON != null && returnJSON.size() > 0) {
						for (Object item : returnJSON) {
							JSONObject valJSON = (JSONObject) item;

							JSONObject ordersResJSON = new JSONObject();
							ordersResJSON.put("order_id", valJSON.getString("id"));
							ordersResJSON.put("price", valJSON.get("price") + "");
							ordersResJSON.put("amount", valJSON.get("amount_original") + "");
							String type = valJSON.getString("type");
							//处理下单时间
							Date createDate = new Date(Long.valueOf(valJSON.get("date") + "") * 1000);
							ordersResJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
							ordersResJSON.put("deal_amount", Double.valueOf(valJSON.get("amount_original") + "") - Double.valueOf(valJSON.getString("amount") + ""));

							ordersResJSON.put("symbol", "btc_cny");

							if ("bid".equalsIgnoreCase(type)) {
								type = "0";
							} else if ("ask".equalsIgnoreCase(type)) {
								type = "1";
							}
							ordersResJSON.put("type", type + "");
							ordersResJSON.put("status", valJSON.get("status") + "");

							ordersResArr.add(ordersResJSON);
						}
					}
				}else if(market.equals("LTCCNY")){
					JSONArray returnJSON = (JSONArray) resultResJSON.get("order");
					if (returnJSON != null && returnJSON.size() > 0) {
						for (Object item : returnJSON) {
							JSONObject valJSON = (JSONObject) item;

							JSONObject ordersResJSON = new JSONObject();
							ordersResJSON.put("order_id", valJSON.getString("id"));
							ordersResJSON.put("price", valJSON.get("price") + "");
							ordersResJSON.put("amount", valJSON.get("amount_original") + "");
							String type = valJSON.getString("type");
							//处理下单时间
							Date createDate = new Date(Long.valueOf(valJSON.get("date") + ""));
							ordersResJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
							ordersResJSON.put("deal_amount", Double.valueOf(valJSON.get("amount_original") + "") - Double.valueOf(valJSON.getString("amount") + ""));

							ordersResJSON.put("symbol", "ltc_cny");

							if ("bid".equalsIgnoreCase(type)) {
								type = "0";
							} else if ("ask".equalsIgnoreCase(type)) {
								type = "1";
							}
							ordersResJSON.put("type", type + "");
							ordersResJSON.put("status", valJSON.get("status") + "");

							ordersResArr.add(ordersResJSON);
						}
					}
				}else if(market.equals("LTCBTC")){
					JSONArray returnJSON = (JSONArray) resultResJSON.get("order");
					if (returnJSON != null && returnJSON.size() > 0) {
						for (Object item : returnJSON) {
							JSONObject valJSON = (JSONObject) item;

							JSONObject ordersResJSON = new JSONObject();
							ordersResJSON.put("order_id", valJSON.getString("id"));
							ordersResJSON.put("price", valJSON.get("price") + "");
							ordersResJSON.put("amount", valJSON.get("amount_original") + "");
							String type = valJSON.getString("type");
							//处理下单时间
							Date createDate = new Date(Long.valueOf(valJSON.get("date") + "") * 1000);
							ordersResJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
							ordersResJSON.put("deal_amount", Double.valueOf(valJSON.get("amount_original") + "") - Double.valueOf(valJSON.getString("amount") + ""));

							ordersResJSON.put("symbol", "ltc_btc");

							if ("bid".equalsIgnoreCase(type)) {
								type = "0";
							} else if ("ask".equalsIgnoreCase(type)) {
								type = "1";
							}
							ordersResJSON.put("type", type + "");
							ordersResJSON.put("status", valJSON.get("status") + "");

							ordersResArr.add(ordersResJSON);
						}
					}
				}
				

				// TODO 有数据
				dataJSON.put("ordersList", ordersResArr);
				resultJSON.put("data", dataJSON);
				
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
				
			} else {
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:"
						+ responseJSON.get("error"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取挂单息返回.--原始信息:" + result
					+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e) {
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取挂单失败." + paramsMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis();
		resultJSON.put("consume", (ed - st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 行情API
	 * {"ticker":{"high":"2085.00","low":"1988.71","buy":"2084.15","sell":"2085.40","last":"2085.00","vol":"132020.35270000","date":1419228176,"vwap":2002.73,"prev_close":1998.58,"open":1996.62}}
	 */
	public JSONObject queryTicker(Map<String, String> paramsMap) {

		HTTPUtil httpUtil = new HTTPUtil();
		String symbol = paramsMap.get("symbol");
		if ("ltc_cny".equalsIgnoreCase(symbol)) {
			paramsMap.put("requestURL", "https://data.btcchina.com/data/ticker?market=LTCCNY");
		} else if ("btc_cny".equalsIgnoreCase(symbol)) {
			paramsMap.put("requestURL", "https://data.btcchina.com/data/ticker?market=BTCCNY");
		} else if ("ltc_btc".equalsIgnoreCase(symbol)) {
			paramsMap.put("requestURL", "https://data.bter.com/api/1/ticker/LTCBTC");
		}

		JSONObject resultJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodGet(paramsMap);
			resultJSON = (JSONObject) JSON.parse(result);
		} catch (Exception e) {
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "行情API失败." + paramsMap + ";原始信息:" + result , e);
		}
		return resultJSON;
	}

	/**
	 * depth(市场深度)
	 * {"asks":[[2085.4,0.2],[2085,32.0836],[2084.98,0.08],[2084.76,0.1],[2084.66,0.1982]],"bids":[[2083,10.0468],[2081.08,0.3],[2081.07,0.3665],[2080.83,0.185],[2080.53,0.498]],"date":1419228149}
	 */
	public JSONObject queryDepth(Map<String, String> paramsMap) {
		long st = System.currentTimeMillis();
		// 拼装目标数据
		JSONObject resultJSON = new JSONObject();

		HTTPUtil httpUtil = new HTTPUtil();

		Map<String, String> requestMap = new HashMap<String, String>();
		
		String symbol = "" ; 
		if("ltc_cny".equalsIgnoreCase(paramsMap.get("moneytype") + ""))
		{
			symbol = "?market=ltccny" ; 
		}
		
		requestMap.put("requestURL", "https://data.btcchina.com/data/orderbook" + symbol);

		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodGet(requestMap);
			responseJSON = (JSONObject) JSON.parse(result);
			// responseJSON = (JSONObject)
			// responseJSON.get(paramsMap.get("moneytype"));

			// 拼装符合条件的json数据
			JSONObject dataJSON = new JSONObject();

			int count = 0;
			// 按照规则排序的容器
			Map<Double, JSONObject> asksMap = new TreeMap<Double, JSONObject>();
			JSONArray asksResArr = new JSONArray();
			JSONArray asksArr = (JSONArray) responseJSON.get("asks");
			for (Iterator iterator = asksArr.iterator(); iterator.hasNext();) {
				JSONArray asksTempArr = (JSONArray) iterator.next();
				JSONObject askJSON = new JSONObject();
				askJSON.put("count", "1");
				askJSON.put("vol", asksTempArr.get(1) + "");
				askJSON.put("rate", asksTempArr.get(0) + "");

				asksMap.put(Double.valueOf(askJSON.get("rate") + ""), askJSON);
			}

			for (Iterator iterator = asksMap.entrySet().iterator(); iterator.hasNext();) {
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE) {
					break;
				}

				JSONObject asksTemp = (JSONObject) me.getValue();

				asksResArr.add(asksTemp);
				count++;
			}

			dataJSON.put("asks", asksResArr);

			// 按照规则排序的容器
			count = 0;
			Map<Double, JSONObject> bidsMap = new TreeMap<Double, JSONObject>(
					new Comparator<Double>() {
						@Override
						public int compare(Double o1, Double o2) {
							return o2.compareTo(o1);
						}
					});
			JSONArray bidsResArr = new JSONArray();
			JSONArray bidsArr = (JSONArray) responseJSON.get("bids");
			for (Iterator iterator = bidsArr.iterator(); iterator.hasNext();) {
				JSONArray bidsTempArr = (JSONArray) iterator.next();
				JSONObject bidsJSON = new JSONObject();
				bidsJSON.put("count", "1");
				bidsJSON.put("vol", bidsTempArr.get(1) + "");
				bidsJSON.put("rate", bidsTempArr.get(0) + "");

				bidsMap.put(Double.valueOf(bidsJSON.get("rate") + ""), bidsJSON);
			}

			for (Iterator iterator = bidsMap.entrySet().iterator(); iterator.hasNext();) {
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE) {
					break;
				}

				JSONObject bidsTemp = (JSONObject) me.getValue();

				bidsResArr.add(bidsTemp);
				count++;
			}
			dataJSON.put("bids", bidsResArr);

			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			resultJSON.put("data", dataJSON);
		} catch (Exception e) {
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "depth(市场深度)失败." + paramsMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis();
		resultJSON.put("consume", (ed - st) + "毫秒");
		return resultJSON;
	}

	/**
	 * trades的格式,历史交易记录
	 */
	public JSONArray queryHistoryTrades(String symbol, Map<String, String> paramsMap) {
		return null;
	}

	/**
	 * 获取所有的行情
	 * 
	 * @return
	 */
	public JSONObject getTrade() {
		return null;
	}

	public void setAuthJSON(JSONObject authJSON) {
		this.authJSON = authJSON;
	}

	@Override
	public String convertMoneyType(String moneytype)
	{
		String result="";
		if("btc_cny".equalsIgnoreCase(moneytype)){
			result="BTCCNY";
		}else if("ltc_cny".equalsIgnoreCase(moneytype)){
			result="LTCCNY";
		}
		return result;
	}

	@Override
	public String toString()
	{
		return "BtcChinaTradeServiceImplay [findid()=" + findWebsiteId() + "]";
	}

	@Override
	public JSONObject getOrdersSingle(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis();
		// 拼装目标数据
		JSONObject resultJSON = new JSONObject();

		// 开发版本
		if ("1".equalsIgnoreCase(ConstatFinalUtil.SYS_BUNDLE.getString("dev.version"))) {
			// 模拟假数据
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("ordersList", new JSONArray());

			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "---模拟下单---" + paramsMap);
			return resultJSON;
		}
		
		HTTPUtil httpUtil = new HTTPUtil();
		String market = this.convertMoneyType(paramsMap.get("moneytype"));
		String paramsStr="["+ paramsMap.get("order_id") +",\""+market+"\"]";
		String nonce = this.findReqtime();
		long id = this.getGeneratedId();
		String params = String.format("tonce=%s&accesskey=%s&requestmethod=%s&id=%d&method=%s&params=%s", nonce, authJSON.getString("Key"), "post", id, "getOrder", paramsMap.get("order_id") + ","+market+"");
	    //ConstatFinalUtil.SYS_LOG.error("signature message: "+params );
	    String hash=EncryptUtil.BtcChinaHmacSHA1(params,authJSON.getString("Secret"));
	    //System.out.println(hash);
	    String userpass = authJSON.getString("Key")+ ":" + hash;
	    String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
	    //System.out.println(basicAuth);
	    
	    String postStr = String.format("{\"method\": \"%s\", \"params\": %s, \"id\": %s}", 
	    		"getOrder", paramsStr, id);
	    
		Map<String, String> headerMap = new HashMap<String, String>();
		headerMap.put("Json-Rpc-Tonce", nonce);
		headerMap.put("Authorization", basicAuth);
		headerMap.put("requestURL", "https://api.btcchina.com/api_trade_v1.php");
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, postStr);
			//ConstatFinalUtil.SYS_LOG.info(res);
			responseJSON = (JSONObject) JSON.parse(result);
			if (responseJSON != null && responseJSON.get("result")!=null) {
				JSONObject dataJSON = new JSONObject();
				JSONObject resultResJSON = (JSONObject) responseJSON.get("result");
				
				JSONObject valJSON = (JSONObject) resultResJSON.get("order");
				JSONObject ordersResJSON = new JSONObject();
				ordersResJSON.put("order_id", valJSON.getString("id"));
				ordersResJSON.put("price", valJSON.get("price") + "");
				ordersResJSON.put("amount", valJSON.get("amount_original") + "");
				
				//处理下单时间
				Date createDate = new Date(Long.valueOf(valJSON.get("date") + "") * 1000);
				ordersResJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
				String type = valJSON.getString("type");
				ordersResJSON.put("deal_amount", Double.valueOf(valJSON.get("amount_original") + "") - Double.valueOf(valJSON.getString("amount") + ""));

				ordersResJSON.put("symbol", paramsMap.get("moneytype"));

				if ("bid".equalsIgnoreCase(type)) {
					type = "0";
				} else if ("ask".equalsIgnoreCase(type)) {
					type = "1";
				}
				ordersResJSON.put("type", type + "");
				
				/*
				 * 状态。可能值：open、closed 、cancelled、pending 或 error
				 * */
				String status = valJSON.get("status") + "" ; 
				if("open".equalsIgnoreCase(status))
				{
					status = "0" ; 
				}else if("cancelled".equalsIgnoreCase(status))
				{
					status = "-1";
				}else if("closed".equalsIgnoreCase(status))
				{
					status = "2";
				}
				ordersResJSON.put("status", status);
				// TODO 有数据
				dataJSON.put("orders", ordersResJSON);
				resultJSON.put("data", dataJSON);
				
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			} else {
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:"
						+ responseJSON.get("error"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取订单详情返回.--原始信息:" + result
					+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e) {
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取订单详情失败." + paramsMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis();
		resultJSON.put("consume", (ed - st) + "毫秒");
		return resultJSON;
	}

	@Override
	public String parseMoneyType(String moneytype)
	{
		return null;
	}

	@Override
	public String findWebSiteName()
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public JSONObject convertOrders(String moneytype, JSONObject ordersTemp)
	{
		// TODO Auto-generated method stub
		return null;
	}
}
